package com.yonyou.crm.csns.phonebook.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.yonyou.crm.common.rest.util.RequestUtil;
import com.yonyou.crm.common.rest.util.ResponseUtil;
import com.yonyou.crm.csns.phonebook.rmitf.IPhonebookRmService;

@RestController
@RequestMapping(value="/csns/phonebooks")
public class PhonebookCtrl {

	@Autowired
	private IPhonebookRmService service;
	
	@RequestMapping(value = "syn", method = RequestMethod.GET)
	public Object syn(HttpServletRequest request, HttpServletResponse response){
		service.synPersonData();
		return ResponseUtil.getObject();
	}
	
	@RequestMapping(value = "mydept", method = RequestMethod.GET)
	public Object getDeptWithSub(HttpServletRequest request, HttpServletResponse response) {
		
		List<Map<String, Object>> list = service.getDeptWithSub(null);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("data", list);
		return ResponseUtil.getObject(rsMap);
	}
	
	@RequestMapping(value = "organizations", method = RequestMethod.GET)
	public Object getOrganization(HttpServletRequest request, HttpServletResponse response){
		List<Map<String, Object>> list = service.getOrgTree();

		Map<String, Object> rsMap = new HashMap<String, Object>();
		rsMap.put("data", list);
		return ResponseUtil.getObject(rsMap);
	}
	
	@RequestMapping(value = "search", method = RequestMethod.GET)
	public Object search(HttpServletRequest request, HttpServletResponse response){

		JSONObject paramObject = RequestUtil.getParamObject(request);
		String searchKey = paramObject.getString("searchKey");
		
		Map<String, Object> map = service.searchList(searchKey);
		return ResponseUtil.getObject(map);
	}
	
	@RequestMapping(value = "sub", method = RequestMethod.GET)
	public Object getSubs(HttpServletRequest request, HttpServletResponse response) {
		
		JSONObject paramObject = RequestUtil.getParamObject(request);
		Long deptId = null;
		String deptObj = (String)paramObject.get("deptId");
		if (deptObj != null && !deptObj.isEmpty()) {
			deptId = paramObject.getLong("deptId");
		}
		
		List<Map<String, Object>> list = service.getDeptWithSub(deptId);
		Map<String, Object> rsMap = new HashMap<String, Object>();
		if (list.size() == 0) {
			return ResponseUtil.getObject(rsMap);
		}
		rsMap.put("orgChildren", list.get(0).get("orgChildren"));
		rsMap.put("userChildren", list.get(0).get("userChildren"));
		return ResponseUtil.getObject(rsMap);
	}
}
